import { useEffect, useMemo, useRef, useState } from "react"
import { Button, Drawer, Empty, Space, Tabs } from "antd"
import { TextWidget, getMessage } from "@inbiz/react"
import { InbizIcon } from "@inbiz/utils"
import EditModal from "./EditModal"
import BpmnViewer from "@inbiz/basic/BpmnViewer"

const EditDrawer = (props: any) => {
  const { visible, $visible, activeGroupInfo, submit, design, record, editProps = {}, editInfo, $editInfo, saveLoading, findDomain } = props

  const [active, $active] = useState<string>('1')
  const iframeRef: any = useRef()
  const timer: any = useRef()

  // 初始进1页面
  useEffect(() => {
    if (visible) {
      $active('1')
    }
  }, [visible, record])

  // 设置iframe里面页面表单不能点击
  useEffect(() => {
    const find = () => {
      let a = iframeRef.current?.contentWindow?.document?.body?.querySelector?.('form')
      clearTimeout(timer.current)
      if (a) {
        a.style.pointerEvents = 'none'
      } else {
        timer.current = setTimeout(() => {
          find()
        }, 300)
      }
    }
    if (visible) {
      find()
    } else {
      clearTimeout(timer.current)
    }
  }, [visible])

  // 调转表单设计页面
  const jumpFormDesign = (proc?: boolean) => {
    const data = editInfo || record
    design({
      id: data?.id,
      type: data?.formTypes,
      outId: data?.formTypes != '3' ? (data?.association)?.split(',')?.[1] : '',
      route: data?.formTypes != '3' ? (data?.association)?.split(',')?.[0] : '',
      groupId: data?.groupId
    }, proc == true)
  }
  // 调转流程设计页面
  const jumpProcessDesign = () => {
    jumpFormDesign(true)
  }

  // 确定修改
  const drawerSubmit = () => {
    const form = editProps?.editRefs?.current?.getForm()
    submit?.(form, false, true, () => {
      if (active != '1') $active('1')
    })
  }

  // 抽屉头dom
  const renderTitle = () => {
    return <>
      <div className="form-manage-edit-drawer-header">
        {/* 编辑表单 */}
        <span><TextWidget>ProcessManage.edit</TextWidget></span>
        <InbizIcon
          className="close-drawer"
          type="icon-ic-close-bold"
          onClick={() => { $visible(false); $editInfo(null) }}
        />
      </div>
    </>
  }

  // tab头部操作按钮
  const extraBtns = useMemo(() => {
    return (
      <Space>
        {
          (editInfo || record)?.formTypes && (editInfo || record)?.formTypes != '3' && // 自定义类型时不显示表单设计
          <Button onClick={() => jumpFormDesign()}>
            <InbizIcon type="icon-biaodansheji" />
            {/* 表单设计 */}
            <TextWidget>ProcessManage.form_setup</TextWidget>
          </Button>
        }
        <Button onClick={jumpProcessDesign}>
          <InbizIcon type="icon-mokuai-liuchengyinqing" />
          {/* 流程设计 */}
          <TextWidget>ProcessManage.process_design</TextWidget>
        </Button>
        {
          active == '1' &&
          <Button type='primary' onClick={drawerSubmit} loading={saveLoading}>
            <InbizIcon type="icon-baocun1" />
            {/* 保存 */}
            <TextWidget>ProcessManage.save</TextWidget>
          </Button>
        }
      </Space>
    )
  }, [record, editInfo, saveLoading, jumpFormDesign, jumpProcessDesign, drawerSubmit])

  const domian = findDomain(activeGroupInfo?.appId)
  const pathname = process.env.NODE_ENV == 'development' ? `/${domian}` : `/inbiz/web/${domian}`
  const jumpRoute = editInfo?.selectForm?.split(',')?.[0] || record?.Route || record?.selectForm?.split(',')?.[0];
  return (
    <>
      <Drawer
        visible={visible}
        width={820}
        placement="right"
        closable={false}
        title={renderTitle()}
        className='process-manage-edit-drawer'
        destroyOnClose
      >
        <Tabs activeKey={active} onChange={e => $active(e)} tabBarExtraContent={extraBtns}>
          {/* 基本信息 */}
          <Tabs.TabPane tab={getMessage('ProcessManage.info')} key="1">
            <EditModal
              edit={true}
              editData={record}
              processName={props.processName}
              processType={props.processType}
              defaultOption={props.defaultOption}
              {...editProps}
            />
          </Tabs.TabPane>
          {/* 表单详情 */}
          { // 自定义类型时不显示表单详情
            (editInfo || record)?.formTypes && (editInfo || record)?.formTypes != '3' &&
            <Tabs.TabPane tab={getMessage('ProcessManage.form_info')} key="2" forceRender>
              <iframe
                ref={iframeRef}
                className="form-preview"
                src={`${location.origin}${pathname}?v=${(editInfo || record)?.DataVersionId}#/form/${jumpRoute}`}
              ></iframe>
            </Tabs.TabPane>
          }
          {/* 流程详情 */}
          <Tabs.TabPane tab={getMessage('ProcessManage.process_info')} key="3">
            {
              record?.actReProcdefId ?
                <BpmnViewer processId={record?.actReProcdefId} /> :
                <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={<TextWidget>ProcessManage.process_no_data</TextWidget>} />
            }
          </Tabs.TabPane>
        </Tabs>
      </Drawer>
    </>
  )
}

export default EditDrawer